package com.jiepos.mpos.inter.push.getui;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.base.payload.APNPayload.AlertMsg;
import com.gexin.rp.sdk.base.payload.APNPayload.DictionaryAlertMsg;
import com.gexin.rp.sdk.base.payload.Payload;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.AbstractTemplate;
import com.gexin.rp.sdk.template.LinkTemplate;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.gexin.rp.sdk.template.style.Style0;
import com.jiepos.mpos.common.constant.ExceptionConstant;
import com.jiepos.mpos.core.exception.MposException;
import com.jiepos.mpos.core.util.StringUtils;
import com.jiepos.mpos.inter.push.getui.GTPushMessage.PushTemplet;

/**
 * @ClassName: MposPushService
 * @Description: 推送服务
 * @author 孙永
 * @date 2017年10月17日 下午1:36:37
 */
//@Component
public class GTPushService {
	
	private static Logger logger = LoggerFactory.getLogger(GTPushService.class);
	
	//@Autowired
	private GTPush GTPush;
	
	@Autowired
	private IGtPush iGtPush;
	
	/**
	 * 单个用户推送打开应用模板消息
	 * @param title 推送标题
	 * @param text 推送内容
	 * @param clientId 用户唯一标识
	 * @param transmissionContent 透传内容
	 */
	public void pushMessageToSingleNotification(String title, String text, String clientId, String transmissionContent){
		pushMessageToSingle(gerMposPushMessage(PushTemplet.Notification, title, text, null, clientId, transmissionContent, null, null));
	}
	
	/**
	 * 单个用户推送打开链接模板消息
	 * @param title 推送标题
	 * @param text 推送内容
	 * @param url 链接
	 * @param clientId 用户唯一标识
	 */
	public void pushMessageToSingleLink(String title, String text, String url, String clientId){
		pushMessageToSingle(gerMposPushMessage(PushTemplet.Link, title, text, url, clientId, null, null, null));
	}
	
	/**
	 * 单个用户推送透传消息模板消息
	 * @param title 推送标题
	 * @param text 推送内容
	 * @param clientId 用户唯一标识
	 * @param transmissionContent 透传内容
	 */
	public void pushMessageToSingleTransmission(String title, String subTitle, String text, String clientId, String transmissionContent){
		pushMessageToSingle(gerMposPushMessage(PushTemplet.Transmission, title, text, null, clientId, transmissionContent, null, null));
	}
	
	/**
	 * 多个用户推送打开应用模板消息
	 * @param title 推送标题
	 * @param text 推送内容
	 * @param transmissionContent 透传内容
	 * @param taskGroupName 组别
	 * @param clientIds 用户列表
	 */
	public void pushMessageToListNotification(String title, String text, String transmissionContent, String taskGroupName, List<String> clientIds){
		pushMessageToList(gerMposPushMessage(PushTemplet.Notification, title, text, null, null, transmissionContent, taskGroupName, clientIds));
	}
	
	/**
	 * 多个用户推送打开链接模板消息
	 * @param title 推送标题
	 * @param text 推送内容
	 * @param url 链接
	 * @param taskGroupName 组别
	 * @param clientIds 用户列表
	 */
	public void pushMessageToListLink(String title, String text, String url, String taskGroupName, List<String> clientIds){
		pushMessageToList(gerMposPushMessage(PushTemplet.Link, title, text, url, null, null, taskGroupName, clientIds));
	}
	
	/**
	 * 多个用户推送透传消息模板消息
	 * @param title 推送标题
	 * @param text 推送内容
	 * @param transmissionContent 透传内容
	 * @param taskGroupName 组别
	 * @param clientIds 用户列表
	 */
	public void pushMessageToListTransmission(String title, String text, String transmissionContent, String taskGroupName, List<String> clientIds){
		pushMessageToList(gerMposPushMessage(PushTemplet.Transmission, title, text, null, null, transmissionContent, taskGroupName, clientIds));
	}
	
	/**
	 * app整体推送消息
	 * @param title 推送标题
	 * @param text 推送内容
	 * @param transmissionContent 透传内容
	 * @param taskGroupName 组别
	 */
	public void pushMessageToAppNotification(String title, String text, String transmissionContent, String taskGroupName){
		pushMessageToApp(gerMposPushMessage(PushTemplet.Notification, title, text, null, null, transmissionContent, taskGroupName, null));
	}
	
	/**
	 * app整体推送消息
	 * @param title 推送标题
	 * @param text 推送内容
	 * @param url 链接
	 * @param taskGroupName 组别
	 */
	public void pushMessageToAppLink(String title, String text, String url, String taskGroupName){
		pushMessageToApp(gerMposPushMessage(PushTemplet.Link, title, text, url, null, null, taskGroupName, null));
	}
	
	/**
	 * app整体推送消息
	 * @param title 推送标题
	 * @param text 推送内容
	 * @param url 链接
	 * @param taskGroupName 组别
	 */
	public void pushMessageToAppTransmission(String title, String text, String transmissionContent, String taskGroupName){
		pushMessageToApp(gerMposPushMessage(PushTemplet.Transmission, title, text, null, null, transmissionContent, taskGroupName, null));
	}
	
	/**
	 * 单个用户消息推送
	 * @param message
	 */
	private void pushMessageToSingle(GTPushMessage message){
		try{
			/*检验是否有推送目标*/
			if(StringUtils.isBlank(message.getClientId())){
				throw new MposException(ExceptionConstant.PUSH_TARGET_CLIENT_NULL);
			}
			/*设置消息体*/
			SingleMessage singleMessaage = new SingleMessage();
			singleMessaage.setData(getTemplate(message));
			/*设置推送目标*/
			Target target = getSingleTarget(message.getClientId());
			/*开推送*/
			IPushResult result = iGtPush.pushMessageToSingle(singleMessaage, target);
			if(result == null){
				throw new MposException(ExceptionConstant.PUSH_ERROR);
			}
			logger.info("用户标识：{}，推送结果：{}", message.getClientId(), result.getResponse().toString());
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 多个用户消息推送
	 * @param message
	 */
	private void pushMessageToList(GTPushMessage message){
		try{
			/*检验是否有推送目标*/
			if(message.getClientIds() == null || message.getClientIds().isEmpty()){
				throw new MposException(ExceptionConstant.PUSH_TARGET_CLIENT_NULL);
			}
			/*设置消息体*/
			ListMessage listMessage = new ListMessage();
			listMessage.setData(getTemplate(message));
			/*设置推送目标*/
			List<Target> targets = getListTarget(message.getClientIds());
			String taskId = iGtPush.getContentId(listMessage, message.getTaskGroupName());
			IPushResult result = iGtPush.pushMessageToList(taskId, targets);
			if(result == null){
				throw new MposException(ExceptionConstant.PUSH_ERROR);
			}
			logger.info("批量推送结果：{}", result.getResponse().toString());
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * app整体消息推送
	 * @param message
	 */
	private void pushMessageToApp(GTPushMessage message){
		try{
			/*设置消息体*/
			AppMessage appMessage = new AppMessage();
			appMessage.setData(getTemplate(message));
			/*设置app集合*/
			List<String> appIds = new ArrayList<>();
			appIds.add(GTPush.getAppId());
			appMessage.setAppIdList(appIds);
			IPushResult result = iGtPush.pushMessageToApp(appMessage, message.getTaskGroupName());
			if(result == null){
				throw new MposException(ExceptionConstant.PUSH_ERROR);
			}
			logger.info("应用推送结果：{}", result.getResponse().toString());
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 创建推送消息实体
	 * @param title 推送标题
	 * @param text 推送内容
	 * @param url 链接url
	 * @param clientId 用户唯一标识
	 * @param transmissionContent 透传内容
	 * @param taskGroupName 组别
	 * @param clientIds 用户列表
	 * @return
	 */
	private GTPushMessage gerMposPushMessage(PushTemplet templet, String title, String text, String url, String clientId, String transmissionContent, 
			String taskGroupName, List<String> clientIds){
		GTPushMessage message = new GTPushMessage();
		message.setPushTemplet(templet);
		message.setClientId(clientId);
		message.setText(text);
		message.setTitle(title);
		message.setUrl(url);
		message.setTransmissionContent(transmissionContent);
		message.setTaskGroupName(taskGroupName);
		message.setClientIds(clientIds);
		return message;
	}
	
	/**
	 * 获取单个推送目标
	 * @param clientId
	 * @return
	 */
	private Target getSingleTarget(String clientId){
		return getTarget(new String[]{clientId}).get(0);
	}
	
	/**
	 * 获取多个推送目标
	 * @param clientIds
	 * @return
	 */
	private List<Target> getListTarget(List<String> clientIds){
		return getTarget(clientIds.toArray(new String[clientIds.size()]));
	}
	
	/**
	 * 获取推送目标
	 * @param clientIds
	 * @return
	 */
	private List<Target> getTarget(String[] clientIds){
		List<Target> targets = new ArrayList<>();
		for(String clientId : clientIds){
			Target target = new Target();
			target.setAppId(GTPush.getAppId());
			target.setClientId(clientId);
			targets.add(target);
		}
		return targets;
	}
	
	/**
	 * 获取推送模板
	 * @param message
	 * @return
	 */
	private AbstractTemplate getTemplate(GTPushMessage message){
		/*推送条件检验*/
		if(StringUtils.isBlank(message.getUrl()) && StringUtils.isBlank(message.getTransmissionContent())){
			throw new MposException(ExceptionConstant.PUSH_LINKURL_OR_TCONTENT_NULL);
		}
		/*获取推送模板*/
		AbstractTemplate template = null;
		if(PushTemplet.Notification.equals(message.getPushTemplet())){
			template = getNotificationTemplate(message);
		}else if(PushTemplet.Link.equals(message.getPushTemplet())){
			template = getLinkTemplate(message);
		}else if(PushTemplet.Transmission.equals(message.getPushTemplet())){
			template = getTransmissionTemplate(message);
		}else{
			throw new MposException(ExceptionConstant.PUSH_TEMPLET_NOT_EXIST);
		}
		return template;
	}
	
	/**
	 * 点击通知打开网页模板
	 * @param message
	 * @return
	 */
	private LinkTemplate getLinkTemplate(GTPushMessage message){
		LinkTemplate template = new LinkTemplate();
		template.setAppId(GTPush.getAppId());
		template.setAppkey(GTPush.getAppKey());
		template.setUrl(message.getUrl());
		template.setStyle(getStyle0(message.getTitle(), message.getText()));
		return template;
	}
	
	/**
	 * 点击通知打开应用模板
	 * @param message
	 * @return
	 */
	private NotificationTemplate getNotificationTemplate(GTPushMessage message){
		NotificationTemplate template = new NotificationTemplate();
		template.setAppId(GTPush.getAppId());
		template.setAppkey(GTPush.getAppKey());
		template.setTransmissionType(GTPush.getTransmissionType());
		template.setTransmissionContent(message.getTransmissionContent());
		template.setStyle(getStyle0(message.getTitle(), message.getText()));
		return template;
	}
	
	/**
	 * 透传消息模版
	 * @param message
	 * @return
	 */
	private TransmissionTemplate getTransmissionTemplate(GTPushMessage message){
		TransmissionTemplate template = new TransmissionTemplate();
		template.setAppId(GTPush.getAppId());
		template.setAppkey(GTPush.getAppKey());
		template.setTransmissionType(GTPush.getTransmissionType());
		template.setTransmissionContent(message.getTransmissionContent());
		template.setAPNInfo(getAPNPayload(message.getTitle(), message.getSubTitle(), message.getText()));
		return template;
	}
	
	/**
	 * 设置通知样式
	 * @param title 通知标题
	 * @param text 通知内容
	 * @return
	 */
	private Style0 getStyle0(String title, String text){
		Style0 style0 = new Style0();
		style0.setLogo(GTPush.getLogo()); // 设置通知图标
		style0.setRing(GTPush.getIsRing()); // 设置是否响铃
		style0.setVibrate(GTPush.getIsVibrate()); // 设置是否震动
		style0.setClearable(GTPush.getIsClearable()); // 设置是否可清除
		style0.setTitle(title); // 设置标题
		style0.setText(text); // 设置内容
		return style0;
	}
	
	private Payload getAPNPayload(String title, String subTitle, String text){
		APNPayload apnPayload = new APNPayload();
		apnPayload.setAutoBadge(GTPush.getAutoBadge());// 设置角标
		apnPayload.setContentAvailable(GTPush.getContentAvailable());
//		apnPayload.setAlertMsg(getAlertMsg(title, subTitle, text));// 设置通知消息体
		return apnPayload;
	}
	
	/**
	 * 设置通知弹窗消息
	 * @param title 标题
	 * @param subTitle 副标题
	 * @param text 内容
	 * @return
	 */
	private AlertMsg getAlertMsg(String title, String subTitle, String text){
		DictionaryAlertMsg alertMsg = new DictionaryAlertMsg();
		alertMsg.setBody(text); // 设置通知文本消息字符串
		alertMsg.setTitle(title); // 设置通知标题
		alertMsg.setSubtitle(subTitle); // 设置副标题
		return alertMsg;
	}
}
